package com.sharedmobility.servlet;

import com.google.gson.Gson;
import com.sharedmobility.dao.UserDAO;
import com.sharedmobility.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/user/profile")
public class UserProfileServlet extends HttpServlet {
    private final UserDAO userDAO = new UserDAO();
    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            // 获取当前登录用户ID
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            
            if (userId == null) {
                throw new Exception("用户未登录");
            }

            // 获取用户信息
            User user = userDAO.findById(userId);
            if (user == null) {
                throw new Exception("用户不存在");
            }

            // 返回用户信息
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("data", user);
            
            response.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(gson.toJson(result));
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            // 获取当前登录用户ID
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            
            if (userId == null) {
                throw new Exception("用户未登录");
            }

            // 获取请求数据
            Map<String, Object> requestData = gson.fromJson(request.getReader(), Map.class);
            String username = (String) requestData.get("username");
            String phone = (String) requestData.get("phone");
            String email = (String) requestData.get("email");
            String address = (String) requestData.get("address");

            // 验证数据
            if (username == null || username.trim().isEmpty()) {
                throw new Exception("用户名不能为空");
            }
            if (phone == null || !phone.matches("\\d{11}")) {
                throw new Exception("手机号格式不正确");
            }
            if (email == null || !email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
                throw new Exception("邮箱格式不正确");
            }

            // 获取用户信息
            User user = userDAO.findById(userId);
            if (user == null) {
                throw new Exception("用户不存在");
            }

            // 更新用户信息
            user.setUsername(username);
            user.setPhone(phone);
            user.setEmail(email);
            user.setAddress(address);

            if (!userDAO.update(user)) {
                throw new Exception("更新用户信息失败");
            }

            // 返回成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "个人资料更新成功");
            
            response.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(gson.toJson(result));
        }
    }
} 